#pragma once
#include<iostream>
#include<vector>
#include<assert.h>
using namespace std;

template<class K, class V>
struct AVLTreeNode
{
	pair<K, V> _kv; //第一个数据(_kv.first)存key，第二个数据(_kv.second)存value
	AVLTreeNode<K, V>* _left;
	AVLTreeNode<K, V>* _right;
	AVLTreeNode<K, V>* _parent;
	int _bf; //平衡因子

	AVLTreeNode(const pair<K, V>& kv)
		:_kv(kv),
		_left(nullptr),
		_right(nullptr),
		_parent(nullptr),
		_bf(0)
	{
	}
};
template<class K, class V>
class AVLTree
{
	typedef AVLTreeNode<K, V> Node;
public:
	AVLTree() = default;
	~AVLTree()
	{
		Destory(_root);
	}
	// 插入
	bool Insert(const pair<K, V>& kv)
	{
		if (_root == nullptr)
		{
			_root = new Node(kv);
			return true;
		}
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_kv.first < kv.first)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_kv.first > kv.first)
			{
				parent = cur;
				cur = cur->_left;
			}
			else {
				return false;
			}
		}
		cur = new Node(kv);
		if (parent->_kv.first < kv.first)
		{
			parent->_right = cur;
		}
		else {
			parent->_left = cur;
		}
		cur->_parent = parent;

		//更新平衡因子
		while (parent)
		{
			if (cur == parent->_left)
				parent->_bf--;
			else
				parent->_bf++;
			if (parent->_bf == 0)
				break;
			else if (parent->_bf == 1 || parent->_bf == -1)
			{
				cur = parent;
				parent = parent->_parent;
			}
			else if (parent->_bf == 2 || parent->_bf == -2)
			{
				// 不平衡了，旋转处理

				// parent和cur都是左子树高，进行右单旋
				if (parent->_bf == -2 && cur->_bf == -1) {
					RotateR(parent);
				}
				// parent和cur都是右子树高，进行左单旋
				else if (parent->_bf == 2 && cur->_bf == 1) {
					RotateL(parent);
				}
				// parent是左子树高，cur是右子树高，进行左右双旋
				else if (parent->_bf == -2 && cur->_bf == 1)
				{
					RotateLR(parent);
				}
				// parent是右子树高，cur是左子树高，进行右左双旋
				else if (parent->_bf == 2 && cur->_bf == -1) {
					RotateRL(parent);
				}
				// 旋转后子树平衡了，并且没有改变子树的高度，就不需要继续向上更新平衡因子了
				break;
			}
			// 平衡因子的值只有以上几种情况，其他情况都不可能，如果有直接报错
			else {
				assert(false);
			}
		}
		return true;
	}

	// 删除
	bool Erase(const K& key)
	{
		// 如果为空树就删除不了返回false
		if (_root == nullptr) return false;

		Node* cur = Find(key);
		Node* parent = nullptr;
		// 如果没找到指定节点则返回false
		if (cur == nullptr) return false;

		parent = cur->_parent;
		// 要删除的节点有两个孩子
		if (cur->_left && cur->_right) {
			// 找到右子树的最小节点
			Node* minRight = cur->_right;
			Node* minRightParent = cur;
			while (minRight->_left)
			{
				minRightParent = minRight;
				minRight = minRight->_left;
			}
			// 替换
			cur->_kv = minRight->_kv;

			cur = minRight;
			parent = minRightParent;
		}

		// 要删除的节点有0个或1个孩子
		Node* child = nullptr;
		if (cur->_left) child = cur->_left;
		else child = cur->_right;

		if (child) child->_parent = parent;
		if (parent == nullptr) {
			// 如果被删除节点是根节点，则它的孩子节点作为根节点
			_root = child;
		}
		else {
			if (parent->_left == cur) {
				parent->_left = child;
				parent->_bf++; //左子树高度减少
			}
			else {
				parent->_right = child;
				parent->_bf--; //右子树高度减少
			}
		}

		//从父节点开始向上调整平衡因子
		Node* ppNode = parent;
		while (ppNode)
		{
			Node* pParent = ppNode->_parent;
			if (ppNode->_bf == 1 || ppNode->_bf == -1) {
				// 子树高度没有变化，直接退出
				break;
			}
			else if (ppNode->_bf == 0) {
				// 继续向上更新
				if (pParent == nullptr) break;
				if (pParent->_left == ppNode) {
					pParent->_bf++;
				}
				else {
					pParent->_bf--;
				}
				ppNode = pParent;
			}
			else if (ppNode->_bf == 2 || ppNode->_bf == -2)
			{
				bool IsLeft = false;
				if (pParent && pParent->_left == ppNode) IsLeft = true;

				if (ppNode->_bf == -2 && ppNode->_left->_bf == -1) {
					// 右单旋
					RotateR(ppNode);
					// 向上更新平衡因子
					if (pParent) {
						if (IsLeft) {
							pParent->_bf++;
						}
						else {
							pParent->_bf--;
						}
					}
				}
				else if (ppNode->_bf == -2 && ppNode->_left->_bf == 1) {
					// 左右双旋
					RotateLR(ppNode);
					// 向上更新平衡因子
					if (pParent) {
						if (IsLeft) {
							pParent->_bf++;
						}
						else {
							pParent->_bf--;
						}
					}
				}
				else if (ppNode->_bf == -2 && ppNode->_left->_bf == 0) {
					Node* LNode = ppNode->_left;
					// 右单旋
					RotateR(ppNode);
					// 更新平衡因子
					ppNode->_bf = -1;
					LNode->_bf = 1;
					break; // 子树高度没有变化
				}
				else if (ppNode->_bf == 2 && ppNode->_right->_bf == 1) {
					// 左单旋
					RotateL(ppNode);
					// 向上更新平衡因子
					if (pParent) {
						if (IsLeft) {
							pParent->_bf++;
						}
						else {
							pParent->_bf--;
						}
					}
				}
				else if (ppNode->_bf == 2 && ppNode->_right->_bf == -1) {
					// 右左双旋
					RotateRL(ppNode);
					// 向上更新平衡因子
					if (pParent) {
						if (IsLeft) {
							pParent->_bf++;
						}
						else {
							pParent->_bf--;
						}
					}
				}
				else if (ppNode->_bf == 2 && ppNode->_right->_bf == 0) {
					Node* RNode = ppNode->_right;
					// 左单旋
					RotateL(ppNode);
					// 更新平衡因子
					ppNode->_bf = 1;
					RNode->_bf = -1;
					break; // 子树高度没有变化
				}
				else {
					assert(false);
				}
				ppNode = pParent;
			}
		}
		//删除结点
		delete cur;
		return true;
	}

	// 右单旋
	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		subL->_right = parent;
		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;
		Node* parentParent = parent->_parent;
		parent->_parent = subL;
		if (parentParent == nullptr) {
			// 如果parent为根节点则更新根节点
			_root = subL;
			subL->_parent = nullptr;
		}
		else {
			// subL和parentParent建立联系
			if (parentParent->_left == parent) {
				parentParent->_left = subL;
			}
			else {
				parentParent->_right = subL;
			}
			subL->_parent = parentParent;
		}
		// 更新平衡因子
		subL->_bf = parent->_bf = 0;
	}

	//左单旋
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		subR->_left = parent;
		parent->_right = subRL;
		if (subRL)
			subRL->_parent = parent;
		Node* parentParent = parent->_parent;
		parent->_parent = subR;
		if (parentParent == nullptr) {
			// 如果parent为根节点则更新根节点
			_root = subR;
			subR->_parent = nullptr;
		}
		else {
			// subR和parentParent建立联系
			if (parentParent->_left == parent) {
				parentParent->_left = subR;
			}
			else {
				parentParent->_right = subR;
			}
			subR->_parent = parentParent;
		}
		// 更新平衡因子
		subR->_bf = parent->_bf = 0;
	}

	// 左右双旋
	void RotateLR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		int bf = subLR->_bf;

		// 对subL进行左单旋
		RotateL(subL);
		// 对parent进行右单旋
		RotateR(parent);

		// 更新平衡因子
		if (bf == -1) {
			parent->_bf = 1;
			subL->_bf = 0;
			subLR->_bf = 0;
		}
		else if (bf == 1) {
			subL->_bf = -1;
			parent->_bf = 0;
			subLR->_bf = 0;
		}
		else if (bf == 0) {
			parent->_bf = 0;
			subL->_bf = 0;
			subLR->_bf = 0;
		}
		else {
			assert(false);
		}
	}

	//右左双旋
	void RotateRL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;
		int bf = subRL->_bf;

		// 对subR进行右单旋
		RotateR(subR);
		// 对parent进行左单旋
		RotateL(parent);

		//更新平衡因子
		if (bf == -1) {
			parent->_bf = 0;
			subR->_bf = 1;
			subRL->_bf = 0;
		}
		else if (bf == 1) {
			subR->_bf = 0;
			parent->_bf = -1;
			subRL->_bf = 0;
		}
		else if (bf == 0) {
			parent->_bf = 0;
			subR->_bf = 0;
			subRL->_bf = 0;
		}
		else {
			assert(false);
		}
	}

	//查找
	Node* Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (cur->_kv.first < key)
			{
				cur = cur->_right;
			}
			else if (cur->_kv.first > key)
			{
				cur = cur->_left;
			}
			else {
				return cur;
			}
		}
		return nullptr;
	}

	int Height()
	{
		return _Height(_root);
	}

	bool IsBalanceTree()
	{
		return _IsBalanceTree(_root);
	}

	int Size()
	{
		return _Size(_root);
	}

	void InOrder()
	{
		_InOrder(_root);
	}
private:
	int _Size(Node* root)
	{
		if (root == nullptr) return 0;
		return _Size(root->_left) + _Size(root->_right) + 1;
	}
	int _Height(Node* root)
	{
		if (root == nullptr)
			return 0;
		int leftHeight = _Height(root->_left);
		int rigthHeight = _Height(root->_right);
		return max(leftHeight, rigthHeight) + 1;
	}
	bool _IsBalanceTree(Node* root)
	{
		// 空树也是AVL树
		if (root == nullptr) return true;

		// 计算root结点的平衡因子：即root左右子树的高度差
		int leftHeight = _Height(root->_left);
		int rigthHeight = _Height(root->_right);
		int diff = rigthHeight - leftHeight;
		// 如果计算出的平衡因子与root的平衡因子不相等，或者
		// root平衡因子的绝对值超过1，则一定不是AVL树
		if (abs(diff) >= 2) {
			cout << root->_kv.first << "高度差异常" << endl;
			return false;
		}
		if (root->_bf != diff) {
			cout << root->_kv.first << "平衡因子异常" << endl;
			return false;
		}

		// root的左和右如果都是AVL树，则该树一定是AVL树
		return _IsBalanceTree(root->_left) && _IsBalanceTree(root->_right);
	}
	void _InOrder(Node* root)
	{
		if (root == nullptr) return;
		_InOrder(root->_left);
		cout << root->_kv.first << ":" << root->_kv.second << endl;
		_InOrder(root->_right);
	}
	void Destory(Node* root)
	{
		if (root == nullptr) return;
		if (root->_left) Destory(root->_left);
		if (root->_right) Destory(root->_right);
		delete root;
		root = nullptr;
	}
	Node* _root = nullptr;
};

// 测试代码
void TestAVLTree1()
{
	AVLTree<int, int> t1;
	AVLTree<int, int> t2;
	// 常规的测试用例
	int a[] = { 16, 3, 7, 11, 9, 26, 18, 14, 15 };
	// 特殊的带有双旋场景的测试用例
	int b[] = { 4, 2, 6, 1, 3, 5, 15, 7, 16, 14 };
	for (auto e : a)
	{
		t1.Insert({ e, e });
	}
	t1.InOrder();
	cout << t1.IsBalanceTree() << endl;

	for (auto e : b)
	{
		t2.Insert({ e, e });
	}
	t2.InOrder();
	cout << t2.IsBalanceTree() << endl;
}
// 插入一堆随机值，测试平衡，顺便测试一下高度和性能等
void TestAVLTree2()
{
	const int N = 1000000;
	vector<int> v;
	v.reserve(N);
	srand(time(0));
	for (size_t i = 0; i < N; i++)
	{
		v.push_back(rand() + i);
	}
	size_t begin2 = clock();
	AVLTree<int, int> t;
	for (auto e : v)
	{
		t.Insert(make_pair(e, e));
	}
	size_t end2 = clock();
	cout << "Insert:" << end2 - begin2 << endl;
	cout << t.IsBalanceTree() << endl;
	cout << "Height:" << t.Height() << endl;
	cout << "Size:" << t.Size() << endl;
	size_t begin1 = clock();
	// 确定在的值
	/*for (auto e : v)
	{
		t.Find(e);
	}*/
	// 随机值
	for (size_t i = 0; i < N; i++)
	{
		t.Find((rand() + i));
	}
	size_t end1 = clock();
	cout << "Find:" << end1 - begin1 << endl;
}

void TestErase()
{
	const int N = 100000;
	vector<int> v;
	v.reserve(N);
	srand(time(0));
	for (size_t i = 0; i < N; i++)
	{
		v.push_back(rand() + i);
	}
	size_t begin2 = clock();
	AVLTree<int, int> t;
	for (auto e : v)
	{
		t.Insert(make_pair(e, e));
	}
	size_t end2 = clock();
	cout << "Insert:" << end2 - begin2 << endl;
	cout << t.IsBalanceTree() << endl;
	cout << "Height:" << t.Height() << endl;
	cout << "Size:" << t.Size() << endl;

	size_t begin1 = clock();
	//// 随机删除500个数据
	//for (int i = 0; i < 500; i++) {
	//	t.Erase(v[rand() + i]);
	//	if (!t.IsBalanceTree()) {
	//		cout << "AVL树不平衡，删除节点有误" << endl;
	//		break;
	//	}
	//}

	// 删除所有节点需要的时间
	for (int i = 0; i < v.size(); i++)
	{
		t.Erase(v[i]);
	}
	size_t end1 = clock();
	cout << t.IsBalanceTree() << endl;
	cout << "Erase:" << end1 - begin1 << endl;
}